package com.pzh.guli.service.oss.service.imp;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.pzh.guli.service.oss.service.FileService;
import com.pzh.guli.service.oss.utils.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;
@Service
public class FileServiceImp implements FileService {
    @Autowired
    private OssProperties ossProperties;
    //oss文件上传
    public String upload(InputStream inputStream, String module, String originalFileName) {
        String endpiont = ossProperties.getEndpoint();
        String keyid = ossProperties.getKeyid();
        String keydercret = ossProperties.getKeysercret();
        String bucketname = ossProperties.getBucketname();
        System.out.println(endpiont+keyid+keydercret+keydercret);
        OSS oss=new OSSClientBuilder().build(endpiont,keyid,keydercret);
        System.out.println(oss.doesBucketExist(bucketname));
        //判断是否存在
        if (!oss.doesBucketExist(bucketname)){ //不存在就创建
            oss.createBucket(bucketname);
            oss.setBucketAcl(bucketname, CannedAccessControlList.PublicRead); //设置权限 公开可读
        }
        //构建路径
        String directory = new DateTime().toString("yyyy/MM/dd");//时间构建目录
        String fileName= UUID.randomUUID().toString();//文件名
        String fileExtension=originalFileName.substring(originalFileName.lastIndexOf("."));//文件扩展名
        String key=module+"/"+directory+"/"+fileName+fileExtension;//完整地址
        //上传
        oss.putObject(bucketname,key,inputStream);
        oss.shutdown();
        return "https://"+bucketname+"."+endpiont+"/"+key;
    }

    @Override
    public void removeFile(String url) {
        String endpiont = ossProperties.getEndpoint();
        String keyid = ossProperties.getKeyid();
        String keydercret = ossProperties.getKeysercret();
        String bucketname = ossProperties.getBucketname();
        OSS oss=new OSSClientBuilder().build(endpiont,keyid,keydercret);
        String host="https://"+bucketname+"."+endpiont+"/";
        String objectName=url.substring(host.length());
        //删除文件
        oss.deleteObject(bucketname,objectName);
        oss.shutdown();
    }
}
